<template>
  <div class="app-container search-list-container poll">
    <div class="search-wrapper">
      <!-- 选择栏目 -->
      <el-form
        :model="queryInfo"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="auto"
      >
        <el-form-item label="消息标题" prop="messageTitle">
          <el-input
            v-model="queryInfo.messageTitle"
            placeholder="请输入消息标题"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="expireDate">
          <el-date-picker
            size="small"
            v-model="queryInfo.expireDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="消息状态" prop="read">
          <el-select clearable v-model="queryInfo.read" placeholder="请选择">
            <el-option
              v-for="item in messageMethodData"
              :key="item.lable"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息类型" prop="messageType">
          <el-select
            clearable
            v-model="queryInfo.messageType"
            placeholder="请选择"
          >
            <el-option
              v-for="item in messageTypeData"
              :key="item.value"
              :label="item.lable"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </div>
      </el-form>
    </div>
    <!-- 批量已读按钮操作 -->
    <div class="list-wrapper">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-chat-dot-square"
            size="mini"
            @click="AllRead"
            :disabled="multiple"
            >批量已读</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:messagereceive:export']"
            >导出</el-button
          >
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>

      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="infoList"
        height="100%"
        width="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="checkSelect">
        </el-table-column>
        <el-table-column
          label="消息状态"
          center
          :render-header="renderHeader"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span
              class="text-status"
              :class="{
                green: scope.row.read == true,
                yellow: scope.row.read == false,
              }"
              >{{ scope.row.read == true ? "已读" : "未读" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="标题"
          align="center"
          prop="messageTitle"
          :render-header="renderHeader"
          show-overflow-tooltip
        />
        <el-table-column
          label="消息内容"
          align="center"
          prop="messageContext"
          :render-header="renderHeader"
          show-overflow-tooltip
        />

        <el-table-column
          label="消息类型"
          align="center"
          prop="messageTypeToString"
          :render-header="renderHeader"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="发送单位"
          align="center"
          prop="deptName"
          :render-header="renderHeader"
          show-overflow-tooltip
        >
        </el-table-column>
        <!-- <el-table-column
          label="发送状态"
          align="center"
          prop="sendStatus"
          :render-header="renderHeader"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span
              class="text-status"
              :class="{
                green: scope.row.sendStatus == 1,
                yellow: scope.row.sendStatus == 0,
              }"
              >{{ scope.row.sendStatus == 1 ? "已发送" : "未发送" }}</span
            >
          </template>
        </el-table-column> -->
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :render-header="renderHeader"
          show-overflow-tooltip
        />
        <el-table-column
          label="发送时间 "
          align="center"
          prop="expireDate "
          :render-header="renderHeader"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.delayTime ? scope.row.delayTime : scope.row.createTime
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
              v-hasPermi="['system:message:detail']"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryInfo.current" :limit.sync="queryInfo.size"
        @pagination="getList" /> -->

      <div class="pagenation-box">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.current"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="queryInfo.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="text-align: right"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 新增修改 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      :class="juBge ? 'frame-detail' : 'frame-edit'"
      @close="closeAdd"
    >
      <el-form
        ref="form"
        :disabled="juBge"
        :model="form"
        :rules="rules"
        label-width="81px"
      >
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog
      :title="title"
      :visible.sync="openCheck"
      width="600px"
      :class="juBge ? 'frame-detail' : 'frame-edit'"
    >
      <div style="font-size: 16px">{{ form.messageTitle }}</div>
      <div style="margin: 20px 0px 20px 20px">
        <span style="width: 40px"></span>{{ form.messageContext }}
      </div>
      <div style="text-align: right">时间：{{ form.createTime }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openCheck = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllListReceiveInfo,
  getReceiveInfo,
  getMessageContent,
  AlreadyRead,
} from "@/api/insideMessage/management";
import secondVue from "../../../components/Crontab/second.vue";

export default {
  name: "Info",
  inject: ["reload"],
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      juBge: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 终端鉴权白名单表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryInfo: {
        expireDate: "",
        Date: "",
        startTime: "",
        endTime: "",
        messageTitle: "",
        messageType: "",
        read: "",
        userId: "",
        current: 1,
        size: 10,
      },
      messageTypeData: [
        {
          lable: "系统消息",
          value: 0,
        },
        {
          lable: "通知公告",
          value: 1,
        },
        {
          lable: "告警消息",
          value: 2,
        },
      ],
      messageMethodData: [
        {
          value: "false",
          label: "未读",
        },
        {
          value: "true",
          label: "已读",
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "请输入终端编码", trigger: "blur" },
        ],
        macAddress: [
          { required: true, message: "请输入MAC地址", trigger: "blur" },
        ],
        ipAddress: [
          { required: true, message: "请输入IP地址", trigger: "blur" },
        ],
        expireDate: [
          {
            required: true,
            message: "选择过期时间",
            trigger: "change",
          },
        ],
      },
      openCheck: false,
      multipleSelection: [], // 多选
      readSelection: [], //判断已读
    };
  },
  created() {
    this.queryInfo.userId = window.localStorage.getItem("userId");
    this.getList();
  },
  methods: {
    /** 获取全部消息单列表 */
    getList() {
      this.loading = true;
      if (this.queryInfo.expireDate) {
        this.queryInfo.startTime = this.queryInfo.expireDate[0] + " 00:00:00";
        this.queryInfo.endTime = this.queryInfo.expireDate[1] + " 23:59:59";
      } else {
        this.queryInfo.startTime = "";
        this.queryInfo.endTime = "";
      }
      getAllListReceiveInfo(this.queryInfo).then((response) => {
        this.infoList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
        this.readSelection = this.infoList.filter((item) => item.read != true);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // this.queryInfo = {
      //   idCode: null,
      //   deivceName: null,
      //   macAddress: null,
      //   ipAddress: null,
      //   expireDate: null,
      //   entitlementUnit: null,
      // };
      this.queryInfo = {
        expireDate: "",
        Date: "",
        startTime: "",
        endTime: "",
        messageTitle: "",
        messageType: "",
        read: "",
        userId: window.localStorage.getItem("userId"),
        current: 1,
        size: 10,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryInfo.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** AllRead 批量已读按钮操作 */
    AllRead() {
      let newarr = this.multipleSelection;
      this.multipleSelection = [];
      newarr.forEach((element) => {
        this.multipleSelection.push(element.id);
      });
      let data = {
        messageList: this.multipleSelection,
        userId: window.localStorage.getItem("userId"),
      };
      AlreadyRead(data)
        .then((res) => {
          this.getList();
        })
        .catch((err) => console.log(err));
      // this.juBge = false;
      // this.form = {};
      // this.open = true;
      // this.title = "新增消息";
    },
    handleExport() {
      this.download(
        "/inifrastructure/message/export",
        {
          ...this.queryInfo,
        },
        `messages_${new Date().getTime()}.xlsx`
      );
    },
    /** 查看 */
    handleSee(row) {
      this.juBge = true;
      const id = row.id || this.ids;
      getMessageContent({ messageId: id }).then((response) => {
        this.form = response.data;
        this.openCheck = true;
        this.title = "消息详情";
      });
      let data = {
        messageList: [row.id],
        userId: window.localStorage.getItem("userId"),
      };
      AlreadyRead(data)
        .then((res) => {
          this.$store.dispatch("insideMessage/isReadCounts", {
            userId: localStorage.getItem("userId"),
          });
          this.getList();
        })
        .catch((err) => console.log(err));
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addInfo(this.form).then((response) => {
            this.open = false;
            this.$modal.msgSuccess("新增成功");
            this.getList();
          });
        }
      });
    },
    closeAdd() {
      this.reload();
    },
    renderHeader(h, { column, $index }) {
      // 新建一个 span
      let span = document.createElement("span");
      // 设置表头名称
      span.innerText = column.label;
      // 临时插入 document
      document.body.appendChild(span);
      column.minWidth = span.getBoundingClientRect().width + 20;
      // 移除 document 中临时的 span
      document.body.removeChild(span);
      return h("span", column.label);
    },
    // 选择全部未读消息
    /**
     * row：当前行数据
     * index：当前第几位
     */
    checkSelect(row, index) {
      let isChecked = true;
      if (row.read != true) {
        // 判断里面是否存在某个参数
        isChecked = true;
      } else {
        isChecked = false;
      }
      return isChecked;
    },
    // 表单多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.multiple = !val.length;
    },
    // 分页控制
    handleSizeChange(newsize) {
      this.queryInfo.size = newsize;
      this.getList();
    },
    handleCurrentChange(newpage) {
      this.queryInfo.current = newpage;
      this.getList();
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/assets/styles/system.scss";

// .poll .frame-edit .el-cascader--medium{
//   width: 100% !important;
// }
// .poll .frame-edit .el-select--medium{
//   width: 100% !important;
// }
.poll ::v-deep .el-radio__label {
  color: #fff !important;
}
</style>
